package com.dy.线性表.顺序表;

import com.dy.线性表.Ilist;

import java.util.Arrays;

public class SqList implements Ilist {
    private Object[] listElem;
    private int curLen;//当前长度
    public SqList(int maxSize){
        curLen=0;
        listElem = new Object[maxSize];
    }

    @Override
    public void clear() {
        curLen =0;

    }

    @Override
    public boolean isEmpty() {
        return curLen==0;
    }

    @Override
    public int length() {
        return curLen;
    }

    @Override
    public Object get(int i) throws Exception {
        if(i<0||i>curLen-1){
            throw new Exception("第"+i+"个元素不存在");
        }
        return listElem[i];
    }

    //在第i个元素前插入x
    @Override
    public void insert(int i, Object x) throws Exception {
        if(curLen==listElem.length){
            throw new Exception("线性表已满");
        }
        if(i<0||i>curLen){
            throw new Exception("插入位置不合法");
        }
        for(int j =curLen;j>i;j--){
            listElem[j] = listElem[j-1];
        }
        listElem[i] = x;
        curLen++;
    }

    public void set(int i, Object x) throws Exception {

        if(i<0||i>curLen){
            throw new Exception("位置不合法");
        }

        listElem[i] = x;
    }


    //On时间复杂度

    @Override
    public void remove(int i) throws Exception {

        if(i<0||i>curLen){
            throw new Exception("删除位置不合法");
        }
        for(int j=i;j<curLen;j++){
            listElem[j] = listElem[j+1];
        }
        curLen--;

    }

    @Override
    public int indexOf(Object x) {
        for(int i=0;i<curLen;i++){
            if(listElem[i].equals(x)){
                return i;
            }
        }
        return -1;
    }

    @Override
    public void display() {
        for(int j=0;j<curLen;j++){
            System.out.print(listElem[j]+" ");
        }
        System.out.println();
    }
}
